// 组合模式, 一个文件夹系统, 可以包含文件夹，也可以包含文件

// 文件夹包含类型
type folderInfo = {
  files: any[];
};

// 假设文件类型为字符串或数字
type IFile = string | number;

// 文件夹接口
interface IFolder {
  id: number;
  includes: any;
  open(dom: any): void;
  close(dom: any): void;
}

interface IFolderDom extends HTMLDivElement {
  folder?: IFolder;
}

interface IProps {
  dom: IFolderDom;
  files: any;
  id: number;
}

class Folder implements IFolder {
  id: number;
  includes: any;
  isFirstOpen = false; // 是否是第一次打开
  dom: IFolderDom;
  constructor(props: IProps) {
    this.dom = props.dom;
    this.includes = props.files;
    this.id = props.id;
    console.log(this.dom);
    // 给dom添加事件绑定
    this.bindEvents(this.dom);
  }
  bindEvents(dom: any) {
    const _folder = this;
    dom.addEventListener('click', function(ev: any) {
      ev.stopPropagation();
      if (dom.classList.contains('is-open')) {
        _folder.close(dom);
      } else {
        _folder.open(dom);
      }
    })
  }
  open(dom: any) {
    dom.classList.add('is-open');
    if (!this.isFirstOpen) {
      this.isFirstOpen = true;
      // 创建文件
      this.createFiles();
    }
  }
  close(dom: any) {
    dom.classList.remove('is-open');
  }
  createFiles() {
    const oInner = this.dom.querySelector('.folder-inner');
    this.includes.forEach((fileItem: any) => {
      if (fileItem.files) {
        const oDom = document.createElement('div');
        oDom.setAttribute('class', 'folder');
        oDom.innerHTML = `
          <span class="folder-title">文件夹${fileItem.id}</span>
          <div class="folder-inner"></div>
        `;
        // 创建子文件夹
        oInner.appendChild(oDom);
        
        new Folder({
          id: fileItem.id,
          dom: oDom,
          files: fileItem.files
        });
        
      } else {
        const oDom = document.createElement('div');
        oDom.setAttribute('class', 'file');
        oDom.innerHTML = `文件${fileItem.id}`;
        oInner.appendChild(oDom);
      }
    })
  }
}

export default Folder